package com.chushouya.manager.service.admin.impl;

import com.chushouya.manager.service.admin.*;
import com.general.framework.core.enums.ContextUserType;
import com.general.framework.core.enums.StatusEnum;
import com.general.framework.core.lang.*;
import com.general.framework.core.schema.PageResult;
import com.chushouya.manager.constants.PartnerTypeEnum;
import com.chushouya.manager.dao.entity.PartnerEntity;
import com.chushouya.manager.dao.entity.PartnerUserEntity;
import com.chushouya.manager.dao.repository.PartnerRepository;
import com.chushouya.manager.dao.repository.PartnerUserRepository;
import com.chushouya.manager.dto.admin.partner.PartnerUserListDTO;
import com.chushouya.manager.dto.admin.partner.PartnerUserQuery;
import com.chushouya.manager.dto.admin.partner.PartnerUserSaveDTO;
import com.chushouya.manager.dto.admin.user.AdminExtendInfoDTO;
import com.chushouya.manager.dto.admin.user.CreateAdminUserAccount;
import com.chushouya.manager.dto.admin.user.SimpleAdminUserDTO;
//=====manager.service.admin.*;
import com.chushouya.manager.service.admin.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Slf4j
public class PartnerUserServiceImpl implements PartnerUserService {

    @Resource
    private PartnerUserRepository partnerUserRepository;

    @Resource
    private PartnerRepository partnerRepository;

    @Resource
    private AdminUserService adminUserService;

    @Resource
    private PartnerService partnerService;


    @Resource
    private ClerkService clerkService;

    @Resource
    private AdminTokenService adminTokenService;

    @Override
    public PageResult<PartnerUserListDTO> selectPageResult(PartnerUserQuery query) {
        // 获取分页结果
        PageResult<PartnerUserListDTO> pageResult = PageResult.of(partnerUserRepository.selectPageResult(query), PartnerUserListDTO.class);
        
        // 获取所有合作商信息
        List<PartnerEntity> allPartners = partnerRepository.selectAll();
        
        // 创建合作商ID到名称的映射，提高查询效率
        java.util.Map<Long, String> partnerNameMap = allPartners.stream()
                .collect(java.util.stream.Collectors.toMap(
                    PartnerEntity::getPartnerId,
                    PartnerEntity::getPartnerName,
                    (existing, replacement) -> existing
                ));
        
        // 遍历结果，补齐partnerName
        if (pageResult.getRows() != null) {
            pageResult.getRows().forEach(dto -> {
                if (dto.getPartnerId() != null) {
                    dto.setPartnerName(partnerNameMap.get(dto.getPartnerId()));
                }
            });
        }
        
        return pageResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String add(PartnerUserSaveDTO save) {
        final Long partnerId = save.getPartnerId();
        Check.notNull(partnerId, "渠道ID不能为空");
        final PartnerEntity partner = partnerRepository.selectByPrimaryKey(partnerId);
        Check.notNull(partner, "渠道信息不存在");
        
        // 注册合作商/门店员工登录账号
        Long adminUserId = 0L;
        if (Objects.equals(PartnerTypeEnum.partner.value(), partner.getPartnerType())) {
            CreateAdminUserAccount adminUserCreate = new CreateAdminUserAccount();
            AdminExtendInfoDTO extendInfo = new AdminExtendInfoDTO();
            extendInfo.setPartnerId(partnerId);
            adminUserCreate.setUserType(ContextUserType.ADMIN_PLATFORM);
            adminUserCreate.setUserName(save.getPhone());
            adminUserCreate.setNickName(Strings.format("{}（{}）", partner.getPartnerName(), save.getUserName()));
            adminUserCreate.setPhoneNumber(save.getPhone());
            adminUserCreate.setSex(Numbers.INTEGER_ZERO);
            adminUserCreate.setRemark(Strings.format("{}[{}]的员工账号", PartnerTypeEnum.getDesc(partner.getPartnerType()), partner.getPartnerName()));
            adminUserCreate.setExtendInfo(extendInfo);
            adminUserId = adminUserService.createPartnerUserAccount(adminUserCreate);
        }

        PartnerUserEntity merchantUserEntity = new PartnerUserEntity();
        merchantUserEntity.setAdminUserId(adminUserId);
        merchantUserEntity.setPartnerId(partnerId);
        merchantUserEntity.setUserName(save.getUserName());
        merchantUserEntity.setNickName(Strings.format("{}（{}）", partner.getPartnerName(), save.getUserName()));
        merchantUserEntity.setPhone(save.getPhone());
        merchantUserEntity.setIsMaster(Boolean.FALSE);
        merchantUserEntity.setStatus(StatusEnum.normal.value());
        merchantUserEntity.setCreateTime(Dates.getTimeNow());
        merchantUserEntity.setUpdateTime(Dates.getTimeNow());
        partnerUserRepository.insertSelective(merchantUserEntity);
        return Objects.equals(PartnerTypeEnum.partner.value(), partner.getPartnerType()) ? "账号已创建成功，初始密码为手机号后6位" : "账号已创建成功";
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String edit(PartnerUserSaveDTO save) {
        Check.notNull(save.getPartnerUserId(), "合作商用户ID不能为空");
        
        // 验证用户是否存在
        PartnerUserEntity existingUser = partnerUserRepository.selectByPrimaryKey(save.getPartnerUserId());
        Check.notNull(existingUser, "合作商用户不存在");
        
        PartnerUserEntity update = new PartnerUserEntity();
        update.setPartnerUserId(save.getPartnerUserId());
        update.setNickName(save.getNickName());
        update.setPhone(save.getPhone());
        update.setUpdateTime(Dates.getTimeNow());
        partnerUserRepository.updateByPrimaryKeySelective(update);
        return "修改成功";
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStatus(Long partnerUserId, Integer status) {
        final PartnerUserEntity merchantUserEntity = partnerUserRepository.selectByPrimaryKey(partnerUserId);
        Check.notNull(merchantUserEntity, "用户不存在");
        PartnerUserEntity update = new PartnerUserEntity();
        update.setPartnerUserId(partnerUserId);
        update.setStatus(status);
        update.setUpdateTime(Dates.getTimeNow());
        partnerUserRepository.updateByPrimaryKeySelective(update);
        if (Objects.equals(StatusEnum.disable.value(), status)) {
            adminTokenService.delLoginToken(merchantUserEntity.getAdminUserId());
        }
        adminUserService.changeStatus(merchantUserEntity.getAdminUserId(), status);
    }

    @Override
    public Long savePartnerMasterAccount(PartnerUserSaveDTO save) {
        // 注册合作商账号
        CreateAdminUserAccount adminUserCreate = new CreateAdminUserAccount();
        adminUserCreate.setUserType(ContextUserType.ADMIN_PLATFORM);
        adminUserCreate.setUserName(save.getUserName());
        adminUserCreate.setNickName(save.getNickName());
        adminUserCreate.setPhoneNumber(save.getPhone());
        adminUserCreate.setSex(Numbers.INTEGER_ZERO);
        adminUserCreate.setRemark(Strings.format("合作商{}的主账号", partnerService.getPartnerName(save.getPartnerId())));
        Long adminUserId = adminUserService.createPartnerUserAccount(adminUserCreate);

        Check.notTrue(partnerUserRepository.existsUserName(save.getUserName()), "重复的员工用户名：{}", save.getUserName());
        PartnerUserEntity merchantUserEntity = new PartnerUserEntity();
        merchantUserEntity.setAdminUserId(adminUserId);
        merchantUserEntity.setPartnerId(save.getPartnerId());
        merchantUserEntity.setUserName(save.getUserName());
        merchantUserEntity.setNickName(save.getNickName());
        merchantUserEntity.setPhone(save.getPhone());
        merchantUserEntity.setIsMaster(Boolean.TRUE);
        merchantUserEntity.setStatus(StatusEnum.normal.value());
        merchantUserEntity.setCreateTime(Dates.getTimeNow());
        merchantUserEntity.setUpdateTime(Dates.getTimeNow());
        partnerUserRepository.insertSelective(merchantUserEntity);
        return adminUserId;
    }


    @Override
    public PartnerUserEntity selectByPhone(Long partnerId, String phone) {
        final PartnerUserQuery query = new PartnerUserQuery();
        query.setPartnerId(partnerId);
        query.setPhone(phone);
        return partnerUserRepository.selectOne(query);
    }

    @Override
    public List<SimpleAdminUserDTO> partnerUser(Long partnerId) {
        Check.notNull(partnerId, "合作商ID不能为空");
        final PartnerUserQuery query = new PartnerUserQuery();
        query.setStatus(StatusEnum.normal.value());
        query.setPartnerId(partnerId);
        final List<PartnerUserEntity> partnerUserEntities = partnerUserRepository.selectList(query);
        if (Lists.isEmpty(partnerUserEntities)) {
            return Lists.emptyList();
        }
        return adminUserService.selectSimpleAdminUser(partnerUserEntities.stream().map(PartnerUserEntity::getAdminUserId).collect(Collectors.toList()));
    }

    @Override
    public PartnerUserEntity selectByAdminUserId(Long adminUserId) {
        final PartnerUserQuery query = new PartnerUserQuery();
        query.setAdminUserId(adminUserId);
        return partnerUserRepository.selectOne(query);
    }




}
